//常用的工具方法
let en_js = require('/environment.js');

//showModel,根据配置展示信息
function showModal(content, title, showCancel, cancelText, confirmText, confirmCallBack, cancelCallBack) {
  let config = {
    title: title ? title : "提示",
    content: content,
    showCancel: showCancel ? showCancel : false,
    cancelText: cancelText ? cancelText : "取消",
    confirmText: confirmText ? confirmText : "确定"
  };

  wx.showModal({
    title: config.title,
    content: config.content,
    showCancel: config.showCancel,
    cancelText: config.cancelText,
    confirmText: config.confirmText,
    success: res => {
      if (res.confirm) {
        if (confirmCallBack) {
          confirmCallBack();
        }
      } else {
        if (cancelCallBack) {
          cancelCallBack();
        }
      }
    }
  });
}

//showActionSheet
function showActionSheet(list, callBack) {
  wx.showActionSheet({
    itemList: list,
    success: res => {
      callBack(res);
    },
    fail: res => {
      let msg = res.errMsg;
      let value = msg.indexOf("cancel") != -1;
      if (!value) {
        showToast(msg);
      }
    }
  });
}

//toast
function showToast(title) {
  wx.showToast({
    title: title,
    icon: 'none',
    duration: 3000
  })
}

//showLoading
function showLoading(title) {
  if (title) {
    wx.showLoading({
      title: title,
      mask: true
    });
  } else {
    wx.showLoading({
      title: '正在加载...',
      mask: true
    });
  }
}

//hideLoading
function hideLoading() {
  wx.hideLoading();
}

//判断返回的参数是否合法
function responseMsg(res) {
  if (res.data.message) {
    return res.data.message;
  }
  return "服务器错误！";
}

// 判断返回的参数是否合法
function validResponse(res) {
  if (parseInt(res.data.code) == 200 || parseInt(res.data.code) == 600 || parseInt(res.data.code) == 999 || parseInt(res.data.code) == 700 || parseInt(res.data.code) == 704) {
    //600跳转图片二维码验证
    //999,商品变成限时折扣商品，不能使用优惠券
    //700,商品不在该点位体售卖
    //704,秒杀、拼团活动分享，点击card需判断用户当前点位是否有活动
    return true;
  } else {
    return false;
  }
}

//判断是否为正确的手机号码
function isPhone(number) {
  //判断手机号码是否合法
  if ((/^1\d{10}$/).test(number)) {
    return true;
  } else {
    return false;
  }
}

//打印
function log(res) {
  if (en_js.status != 0) return;
  let data = res.data ? res.data : res;
  console.log(JSON.stringify(data), 'background: #222; color: #bada55');
}


// time小于10的格式化函数
function timeFormat(param) {
  return param < 10 ? '0' + param : param;
}

//页面停止刷新方法
function hidePageLoading(pullDownRefresh) {
  if (pullDownRefresh) {
    wx.stopPullDownRefresh()
  }
}

//是否包含某个字段
function containsKeyString(originString, key) {
  let value = originString.indexOf(key) != -1;
  if (value) {
    return true;
  } else {
    return false;
  }
}

//根据传入的时间戳转换成时分秒
function timestampToTime(timestamp) {
  let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  let Y = date.getFullYear();
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
  let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
  let s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());

  let obj = {
    year: Y,
    month: M,
    day: D,
    hour: h,
    minus: m,
    second: s
  }
  return obj;
}

// 比较两个日期相差的天数
function getDaysBetween(dateString1, dateString2) {
  let startDate = Date.parse(dateString1);
  let endDate = Date.parse(dateString2);
  let days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
  return days;
}

// 根据秒数获取时分秒
function getHrMinSecBySecond(second) {
  let obj = {
    hour: '',
    min: '',
    sec: '',
  };
  let isEnd = 0;
  // 判断
  if (second <= 0) {
    obj = {
      hour: '00',
      min: '00',
      sec: '00',
    };
    isEnd = 1;
  } else if (second > 0) {
    let hour = timeFormat(parseInt(second / (60 * 60)));
    let min = timeFormat(parseInt((second - hour * 60 * 60) / 60));
    let sec = timeFormat(parseInt(second - hour * 60 * 60 - min * 60));
    obj = {
      ...obj,
      hour: hour,
      min: min,
      sec: sec
    }
  }
  return {
    item: obj,
    isEnd: isEnd
  };
}

//判断两个对象的值是否相等
function isObjectValueEqual(a, b) {
  // Of course, we can do it use for in 
  // Create arrays of property names
  let aProps = Object.getOwnPropertyNames(a);
  let bProps = Object.getOwnPropertyNames(b);

  // If number of properties is different,
  // objects are not equivalent
  if (aProps.length != bProps.length) {
    return false;
  }

  for (let i = 0; i < aProps.length; i++) {
    let propName = aProps[i];

    // If values of same property are not equal,
    // objects are not equivalent
    if (a[propName] !== b[propName]) {
      return false;
    }
  }

  // If we made it this far, objects
  // are considered equivalent
  return true;
}

// 检查字符串中是否含有汉字
function containsChinese(val) {
  let reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
  if (reg.test(val)) {
    return true;
  }
  return false;
}

// 获取当前路由的页面名字，比如pages/index/index返回index
function currentPageName() {
  let pages = getCurrentPages();
  let currPage = null;
  if (pages.length) {
    currPage = pages[pages.length - 1];
    let arr = currPage.route.split('/');
    if (arr.length > 0) {
      return arr[arr.length - 1];
    }
    return null;
  }
  return null;
}

/**
 * 检测当前的小程序
 * 是否是最新版本，是否需要下载、更新
 */
function checkUpdateVersion() {
  //判断微信版本是否 兼容小程序更新机制API的使用
  if (wx.canIUse('getUpdateManager')) {
    //创建 UpdateManager 实例
    const updateManager = wx.getUpdateManager();
    //检测版本更新
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        //监听小程序有版本更新事件
        updateManager.onUpdateReady(function () {
          //TODO 新的版本已经下载好，调用 applyUpdate 应用新版本并重启 （ 此处进行了自动更新操作）
          updateManager.applyUpdate();
        })
        updateManager.onUpdateFailed(function () {
          // 新版本下载失败
          wx.showModal({
            title: '已经有新版本喽~',
            content: '请您删除当前小程序，到微信 “发现-小程序” 页，重新搜索打开哦~',
          })
        })
      }
    })
  } else {
    //TODO 此时微信版本太低（一般而言版本都是支持的）
    wx.showModal({
      title: '溫馨提示',
      content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
    })
  }
}

// jsonString
function jsonStringify(obj) {
  return encodeURIComponent(JSON.stringify(obj));
}

//jsonparse
function jsonParse(obj) {
  return JSON.parse(decodeURIComponent(obj));
}

module.exports = {
  showModal: showModal,
  showActionSheet: showActionSheet,
  showToast: showToast,
  showLoading: showLoading,
  hideLoading: hideLoading,
  responseMsg: responseMsg,
  validResponse: validResponse,
  log: log,
  isPhone: isPhone,
  timeFormat: timeFormat,
  hidePageLoading: hidePageLoading,
  containsKeyString: containsKeyString,
  timestampToTime: timestampToTime,
  getHrMinSecBySecond: getHrMinSecBySecond,
  isObjectValueEqual: isObjectValueEqual,
  containsChinese: containsChinese,
  currentPageName: currentPageName,
  getDaysBetween: getDaysBetween,
  checkUpdateVersion: checkUpdateVersion,
  jsonStringify: jsonStringify,
  jsonParse: jsonParse
}